﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Diagnostics.Eventing.Reader;
using System.Configuration;
using System.Threading;

namespace HpcClusterController
{
    public partial class HpcServiceViCOS : ServiceBase
    {
        EventLogWatcher watcher;
        Controller f;

        EventLogQuery subscriptionQuery;

        private string NIC;

        public HpcServiceViCOS()
        {
            InitializeComponent();

            // Get the path for the background Image from app.Config
            this.NIC = ConfigurationManager.AppSettings["NIC"];

            // Initialize HpcEventLog   
            if (!System.Diagnostics.EventLog.SourceExists("HpcSource"))
                System.Diagnostics.EventLog.CreateEventSource("HpcSource", "HpcEventLog");
            HpcEventLog.Log = "HpcEventLog"; 
        }

        private void log(string str)
        {
            HpcEventLog.Source = "FailoverSource";
            HpcEventLog.WriteEntry(str);
        }

        protected override void OnStart(string[] args) // Recieves the NIC to operate on
        {
            log("ViCOS HPC Cluster Controller Service started.");

            if (this.NIC == "0.0.0.0" || this.NIC == "")
            {
                log("Unspecified network interface. Reinstall ViCOS Failover Cluster Controller with a valid Interface.");
            }
            else
            {
                log(String.Format("Using {0} interface", this.NIC));
                Thread workingThread = new Thread(new ThreadStart(workingThreadHandler));
                workingThread.Start();                
            }
            base.OnStart(args);
        }

        private void workingThreadHandler()
        {
            f = new Controller(this.NIC, HpcEventLog);

            subscriptionQuery = new EventLogQuery(
                @"Microsoft-HPC-Scheduler/Operational", // WARNING!!! DIFFERENT NAME IN HPC R1
                PathType.LogName);

            log("Starting Event Watcher.");
            watcher = new EventLogWatcher(subscriptionQuery);
            watcher.Enabled = true;
            watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(f.watcher_EventRecordWritten);
        }



        protected override void OnStop()
        {
            watcher.EventRecordWritten -= f.watcher_EventRecordWritten;
            watcher.Enabled = false;
            log("ViCOS HPC Cluster Controller Service stopped.");
        }
    }
}
